package com.xiaolei.libraryktx

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.FloatRange
import androidx.fragment.app.FragmentActivity
import androidx.viewbinding.ViewBinding
import com.xiaolei.library.Exts.Ext
import com.xiaolei.library.common.ActivityResultFragment
import kotlin.reflect.KClass

/**
 * 设置界面为黑色标题栏文字的模式
 */
inline fun <reified T : Activity> T.darkStatusModel()
{
    Ext.darkStatusModel(this)
}

/**
 * 设置界面为白色标题栏文字的模式
 */
inline fun <reified T : Activity> T.lightStatusModel()
{
    Ext.lightStatusModel(this)
}


/**
 * 调整界面的透明度
 */
inline var Activity.alpha: Float
    set(@FloatRange(from = 0.1, to = 1.0) value) = Ext.setAlpha(this, value)
    get() = Ext.getAlpha(this)

/**
 * 收起软键盘
 */
inline fun <reified T : Activity> T.hideSoftKeyboard()
{
    Ext.hideSoftKeyboard(this)
}

/**
 * 启动页面返回结果
 *
 * @param klass   需要启动得类
 */
inline fun <reified T : FragmentActivity> T.startForResult(
        klass: KClass<out Activity>,
        noinline bundle: (Bundle.() -> Unit)? = null,
        noinline onResult: ((respCode: Int, data: Intent?) -> Unit)? = null
)
{
    Ext.startForResult(this, klass.java, if (bundle == null)
    {
        null
    } else
    {
        Bundle().apply(bundle)
    }, if (onResult == null)
    {
        null
    } else
    {
        ActivityResultFragment.OnActivityResult { resultCode, data ->
            onResult.invoke(resultCode, data)
        }
    })
}

/**
 * 设置ViewBinding
 */
inline fun <reified T : ViewBinding> Activity.setViewBinding(klass: KClass<T>): T
{
    val inflate = klass.java.getDeclaredMethod("inflate", LayoutInflater::class.java)
    val viewBinding = inflate.invoke(null, layoutInflater) as T
    val root = viewBinding.root
    root.tag = viewBinding
    this.setContentView(root)
    return viewBinding
}

/**
 * 在Activity里获取ViewBinding
 */
inline fun <reified T : ViewBinding> Activity.viewBinding(): Lazy<T>
{
    return lazy {
        val klass = T::class.java
        val bind = klass.getDeclaredMethod("bind", View::class.java)
        val decorView = this.window.decorView
        val contentView = decorView.findViewById<ViewGroup>(android.R.id.content)
        if (contentView.childCount == 0)
        {
            setViewBinding(T::class) as T
        } else
        {
            val root = contentView.getChildAt(0)
            var viewBinding = root.tag as? ViewBinding?
            if (viewBinding == null)
            {
                viewBinding = bind.invoke(null, root) as ViewBinding
                root.tag = viewBinding
            }
            viewBinding as T
        }
    }
}